package com.rayboo.config;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.rayboo.service.AdminUserService;
import com.rayboo.util.DateTool;
import com.rayboo.vo.SessionUser;

/**
 * 
 * @author ray
 *
 */
@Component
public class WebSecurityListener
		implements ServletContextAware, ApplicationListener<InteractiveAuthenticationSuccessEvent> {

	private static final Logger log = LoggerFactory.getLogger(WebSecurityListener.class);

	private ServletContext context;

	@Autowired
	private AdminUserService sysUserService;

	public void setServletContext(ServletContext servletContext) {
		if (context != null)
			log.info(context.toString());
		this.context = servletContext;
	}

	@Override
	public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
				.getRequest();
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		User principal = (User) auth.getPrincipal();
		SessionUser user = new SessionUser();
		user.assignUser(sysUserService.findByUsername(principal.getUsername()));
		user.setLoginTime(DateTool.getDateTime().toString());
		log.info(user.toString());
		request.getSession().setAttribute("user", user);
	}
}